import { Channel, UserChannelResponse } from '@/types/data';
import { http } from '@/utils/http';
// import { isAuth } from '@/utils/token';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { RootState } from '@/types/store';
import differenceBy from 'lodash/differenceBy';

const CHANNEL_KEY = 'wyhhhhhh';
// 获取用户频道列表
export const getChannels = createAsyncThunk(
  'home/getChannel',
  async (_, { getState }) => {
    const {
      login: { token },
    } = getState() as RootState;
    console.log(token);

    // 判断用户是否登录
    if (!!token) {
      // 1.如果用户已经登录了  直接发送请求  获取频道列表数据
      const res = await http.get<UserChannelResponse>('/user/channels');
      //   console.log(res);

      return res.data.data.channels;
    }

    // 2.如果用户未登录
    // 2.1判断本地存储中是否有频道列表数据
    const loaclChannels = JSON.parse(
      localStorage.getItem(CHANNEL_KEY) ?? '[]'
    ) as Channel[];

    if (loaclChannels.length === 0) {
      // 2.3如果没有 就发送请求获取默认的频道列表数据
      //   将拿到的默认列表数据 存储在本地

      const res = await http.get<UserChannelResponse>('/user/channels');
      const { channels } = res.data.data;
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels));
      return channels;
    }
    return loaclChannels;
    // 2.2如果有就获取本地频道列表数据
  }
);
// 获取推荐的频道数据
export const getrestChannel = createAsyncThunk(
  'home/getrestChannel',
  async (_, { getState }) => {
    // 获取所有频道
    const res = await http.get<UserChannelResponse>('/channels');
    const { channels: allChannel } = res.data.data;
    // 从频道中去掉用户的频道 得到我的频道
    const {
      home: { userChannel },
    } = getState() as RootState;
    const restChannel = differenceBy(allChannel, userChannel, 'id');
    //  返回我的频道
    return restChannel;
  }
);

type HomeState = {
  // 用户频道列表数据
  userChannel: Channel[];
  restChannel: Channel[];
};

const initialState: HomeState = {
  // 用户频道列表数据
  userChannel: [],
  restChannel: [],
};

const home = createSlice({
  name: 'home',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getChannels.fulfilled, (state, action) => {
      state.userChannel = action.payload;
    });
    builder.addCase(getrestChannel.fulfilled, (state, action) => {
      state.restChannel = action.payload;
    });
  },
});
export default home.reducer;
